import {html} from 'htm/preact';
import {isTextFieldEntryEdited, TextFieldEntry} from "@bpmn-io/properties-panel";
import {useService} from "bpmn-js-properties-panel";
import {updateMultiInstance} from "@/components/activiti/util";
import {getBusinessObject} from "bpmn-js/lib/util/ModelUtil";

const component = {
  id: 'loopCardinality',
  component: LoopCardinality,
  isEdited: isTextFieldEntryEdited
}

if(window['register']) {
  window['register'].regComponent(component.id,component)
}
export default function(element) {
  component['element']=element;
  return component;
}

function getBody(expression) {
  return expression && expression.get('body');
}

function LoopCardinality(props) {
  const { element, id } = props;
  const translate = useService('translate');
  const debounce = useService('debounceInput');
  const bpmnFactory = useService('bpmnFactory');
  const commandStack = useService('commandStack');
  const businessObject = getBusinessObject(element);
  let loopCharacteristics = businessObject.get('loopCharacteristics');
  const getValue = () => {
    if(loopCharacteristics){
      return getBody(loopCharacteristics.get('loopCardinality')) || '';
    }
    return '';
  }

  const setValue = value => {
    return updateMultiInstance(element,businessObject,bpmnFactory,commandStack,undefined,'loopCardinality',{
      body: value
    })
  }

  return html`<${TextFieldEntry}
    id=${ element.id+"-loopCardinality" }
    element=${ element }
    description=${ translate('Maximum number of instances to start, do not fill in the default set size') }
    label=${ translate('LoopCardinality') }
    getValue=${ getValue }
    setValue=${ setValue }
    debounce=${ debounce }
  />`
}

